<template>
    <n-modal class="rr-block" v-model:show="showModal" :on-after-leave="destroy" :mask-closable="false">
        <n-card
            style="width: 75%;height: 650px"
            title="前端监控"
            :bordered="false"
            size="huge"
            role="dialog"
        >
            <template #header-extra>
                <span class="cursor-pointer" @click="showModal = false">关闭</span>
            </template>
            <div class="flex h-full flex-col">
                <div class="monitoring flex-1 bg-gray-100 relative">
                    <div ref="monitoring_ontainer_ref" class="monitoring-container h-full"></div>
                </div>
            </div>
            <template #footer>
            </template>
        </n-card>
    </n-modal>
    <div class="pm-monitoring-sdk-setting" @click="handleClickOpen">✳️</div>
</template>
<script setup>
import install from './packages/install'
import dayjs from 'dayjs'
import {nextTick} from "vue"

const showModal = ref(false);
const monitoring_ontainer_ref = ref()
const PmMonitoringSdk = new install()
import RrwebPlayer from "rrweb-player";
import * as rrweb from "rrweb";
import {customAlphabet} from "nanoid";

let timer = null;
let player = null
onMounted(() => {
    PmMonitoringSdk.init()
    let events = []
    rrweb.record({
        checkoutEveryNms: 200,
        emit(event) {
            events.push({
                time: dayjs().valueOf(),
                content: JSON.stringify(event)
            });
        },
    });
    timer = timer || setInterval(() => {
        PmMonitoringSdk.bulkAdd(events).then((res) => {
            events = []
        })
    }, 2 * 1000)
})

const handleCutTimeVideo = (time) => {
    const date = dayjs().subtract(time, 'millisecond')
    const height = monitoring_ontainer_ref.value.offsetHeight;
    const width = monitoring_ontainer_ref.value.offsetWidth;
    PmMonitoringSdk.getAll({time: dayjs(date).valueOf()}).then((res) => {
        player = new RrwebPlayer({
            target: monitoring_ontainer_ref.value,
            props: {
                events: res.map((item) => item.content),
                width: width,
                height: height - 80
            },
        });
    })
}

const handleClickOpen = () => {
    showModal.value = true
    nextTick(() => {
        handleCutTimeVideo(10 * 60 * 1000)
    })
}
const destroy = () => {
    PmMonitoringSdk.clear()
}
</script>
<style lang="less">
.monitoring-container {
    box-sizing: border-box;
    border: 1px solid #8bc34a;
    border-radius: 5px;
    overflow: hidden;
}

.rr-player {
    box-shadow: none;
    background: none;
}

</style>
